//
//  BKTabBarView.m
//  itv
//
//  Created by Zhang Yinghui on 10/12/11.
//  Copyright 2011 LavaTech. All rights reserved.
//

#import "BKTabBarView.h"
#import "NSArray+x.h"
#import "UIImage+x.h"
#import "UILabel+x.h"
#import "Theme.h"
#import "NSAttributedString+x.h"

#define BKTabBarIndicatorWidth 15
#define BKTabBarIndicatorHeight 20
#define BKTabBarGroupViewMinHeight   24


@interface BKTabBarView()
@property (nonatomic, strong) IBOutlet UIButton *leftIndicator;
@property (nonatomic, strong) IBOutlet UIButton *rightIndicator;
@property (nonatomic, strong) IBOutlet UIView *itemSelectedBackgroundView;
@property (nonatomic, strong) IBOutlet UIView *backgroundView;
@property (nonatomic, strong) NSMutableArray *btns;

@end

@implementation BKTabBarView
@synthesize style = _style;
- (id)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
    }
    return self;
}
- (void)awakeFromNib{
    [super awakeFromNib];
}
- (NSDictionary *)style{
    if (!_style) {
        _style = @{
            @"font":[UIFont systemFontOfSize:12],
            @"textColor":[UIColor colorWithWhite:0.3 alpha:1.0f],
            @"textSelectedColor":[UIColor systemBlueColor]
        };
    }
    return _style;
}
- (void)setStyle:(NSDictionary *)style{
    NSMutableDictionary *newStyle = [NSMutableDictionary dictionaryWithDictionary:_style];
    for (NSString *k in style.allKeys) {
        [newStyle setValue:[style valueForKey:k] forKey:k];
    }
    _style = newStyle;
    if (self.btns.count > 0) {
        for (UIButton *btn in self.btns) {
            [btn setTitleColor:self.style[@"textColor"] forState:UIControlStateNormal];
            [btn setTitleColor:self.style[@"textSelectedColor"] forState:UIControlStateSelected];
        }
    }
    [self.itemSelectedBackgroundView.subviews.firstObject setBackgroundColor:self.style[@"textSelectedColor"]];
}
- (UIView *)itemSelectedBackgroundView{
    if (!_itemSelectedBackgroundView) {
        _itemSelectedBackgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, self.scrollView.bounds.size.height)];
        _itemSelectedBackgroundView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, _itemSelectedBackgroundView.bounds.size.height-2, _itemSelectedBackgroundView.bounds.size.width, 2)];
        lineView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
        lineView.backgroundColor = self.style[@"textSelectedColor"];
        [_itemSelectedBackgroundView addSubview:lineView];
        [self.scrollView insertSubview:_itemSelectedBackgroundView atIndex:0];
    }
    return _itemSelectedBackgroundView;
}
- (float)totalTextWidth{
    float w = 0;
    for (NSDictionary *item in self.items) {
		NSString *title = [item valueForKey:@"title"];
        w += [title sizeWithAttributes:@{NSFontAttributeName:self.style[@"font"]}].width + 10;
    }
    return w;
}
- (void) setItems:(NSArray *)items{
	_items = items ;
    [self.btns makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
	NSInteger n = [items count];
    CGFloat totalTextWidth =  [self totalTextWidth];
    CGFloat itemMargin = 5;
    if ( totalTextWidth <  self.scrollView.frame.size.width) {
        itemMargin = MAX(itemMargin, (self.scrollView.frame.size.width - totalTextWidth)/(n*2));
    }
	NSMutableArray *btns = [NSMutableArray arrayWithCapacity:n];
    CGRect itemFrame = CGRectMake(0, 0, 0, self.scrollView.bounds.size.height);
	for ( NSInteger i=0; i<n; i++) {
        NSDictionary *item = [items objectAtIndex:i];
        CGFloat titleWidth = [[item valueForKey:@"title"] sizeWithAttributes:@{NSFontAttributeName:self.style[@"font"]}].width + 10;
        itemFrame.origin.x += itemMargin;
        itemFrame.size.width = titleWidth;
        
        UIButton *btn = [[UIButton alloc] initWithFrame:itemFrame];
        [btn addTarget:self action:@selector(tapItem:) forControlEvents:UIControlEventTouchUpInside];
        btn.tag = i;
        btn.backgroundColor = [UIColor clearColor];
        btn.titleLabel.font = self.style[@"font"];
        [btn setTitle:[item valueForKey:@"title"] forState:UIControlStateNormal];
        [btn setTitleColor:self.style[@"textColor"] forState:UIControlStateNormal];
        [btn setTitleColor:self.style[@"textSelectedColor"] forState:UIControlStateSelected];
        
		[self.scrollView addSubview:btn];
		[btns addObject:btn];
        itemFrame.origin.x += itemFrame.size.width + itemMargin;
	}
    self.btns = btns;
    self.scrollView.contentSize = CGSizeMake(itemFrame.origin.x, 0);
    self.selectedIndex = _selectedIndex;
}
- (void)layoutSubviews{
    [super layoutSubviews];
    self.items = _items;
}
- (void) tapItem:(UIButton *)button{
    self.selectedIndex = button.tag;
}
- (void) setSelectedIndex:(NSInteger)selectedIndex{
    if (!self.btns || selectedIndex<0 || selectedIndex >= [self.btns count]) {
		return;
	}
    if (_selectedIndex >= 0 && _selectedIndex < self.btns.count) {
        UIButton *previousButton = [self.btns objectAtIndex:_selectedIndex];
        previousButton.selected = NO;
    }
    UIButton *currentButton = [self.btns objectAtIndex:selectedIndex];
    currentButton.selected = YES;
    //选中按钮文字大小
    [UIView animateWithDuration:0.2
    animations:^{
        self.itemSelectedBackgroundView.frame = currentButton.frame;
    }];
    if (_selectedIndex == selectedIndex) {
        return;
    }
    
    _selectedIndex = selectedIndex;
    id item = [self.items objectAtIndex:selectedIndex];
    if (self.delegate && [self.delegate respondsToSelector:@selector(tabBar:didSelectItem:)]) {
        [self.delegate tabBar:self didSelectItem:item];
    }
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
	if (!_leftIndicator || ! _rightIndicator) {
		return;
	}
	float ow = scrollView.contentSize.width - scrollView.bounds.size.width;
	float ox = scrollView.contentOffset.x;
	float p = ox/ow;
	_leftIndicator.alpha = 0.4 + p*0.6;
	_rightIndicator.alpha = 0.4 + (1-p)*0.6;
}
@end

@interface BKTabBarGroupView()<BKTabBarViewDelegate>
@property (nonatomic, strong) UIView *container;
@property (nonatomic, strong) NSArray *bars;
@end
@implementation BKTabBarGroupView

- (void) dealloc{
}
@end

